#include <stdio.h>
#include <libcaptcha.h>

lc_bmp *load_pattern(char *filename, int x, int y, int w, int h) {
  lc_bmp *img = lc_load_png(filename);
  lc_bmp *cropped;

  if (!img) {
    perror("lc_load_png()");
    return NULL;
  }

  cropped = lc_crop_bmp(img, x, y, w, h);

  if (!cropped) {
    perror("lc_crop_bmp()");
    return NULL;
  }

  lc_free(img);

  return cropped;
}

int main() {
  char * str = "withpattern";
  char * fontfile = "../ttf/dejavu.ttf";

  lc_fontBuffer *font = lc_create_font(fontfile);
  lc_arrGlyph *arr;
  lc_bmp * text;
  lc_bmp * pattern;
  lc_bmp * bg;
  lc_bmp * bmp;
  lc_bmp * captcha;

  if (!font) {
    perror("lc_create_font()");
    return 1;
  }

  arr = lc_str_to_arr(font, str, 50, 70);

  if (!arr) {
    perror("lc_str_to_arr()");
    return 1;
  }

  lc_randomize_arr_x(arr, 10);
  lc_randomize_arr_y(arr, 10);

  text = lc_arr_to_bmp(arr);

  if (!text) {
    perror("lc_arr_to_bmp()");
    return 1;
  }

  pattern = load_pattern("../patterns/96b.png", 400, 200, text->w, text->h);
  /* looks great */
/*  lc_save_png("./example4.png", bmp);*/

  if (!pattern) {
    return 1;
  }

  bg = load_pattern("../patterns/96b.png", 300, 20, pattern->w + 20, pattern->h + 20);

  if (!bg) {
    return 1;
  }

  bmp = lc_pattern_apply(pattern, text);

  if (!bmp) {
    perror("lc_pattern_apply()");
    return 1;
  }

  captcha = lc_pattern_merge(bg, bmp, 10, 10);

  if (!captcha) {
    perror("lc_pattern_merge()");
    return 1;
  }

  lc_save_png("./example5.png", captcha);

  lc_free(captcha);
  lc_free(bg);
  lc_free(text);
  lc_free(pattern);
  lc_free(arr);
  lc_free(bmp);
  lc_free(font);
  return 0;
}
